<template>

	<view class="DetailView">
		<view class="content">
			<z-paging ref="paging" :refresher-only="true" :fixed="true" :show-loading-more-no-more-view='false'
				:refresher-enabled="false" :refresher-threshold="0" hide-refresher-when-reload
				hide-refresher-when-enabled>
				<template #top>
					<m-drag-button :style="{ opacity: BtnShow ? 1 : 0, }" :isDock="true" :existTabBar="true"
						:initialBottom="160" @btnClick="scan">
						<template #BtnContent>
							<u-icon name="scan" color="#fff" size="54rpx"></u-icon>
						</template>
					</m-drag-button>
					<u-navbar :fixed="false" title="设备点检" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff"
						@leftClick='leftClick'></u-navbar>
				</template>
				<view class="MainBox">
					<u--form labelPosition="left" :model="baseFormData" :rules="rules" ref="uForm">


						<u-form-item labelWidth="100" label="设备名称" borderBottom :leftIconStyle="{'font-size':'20px'}"
							prop="EquipmentName" required leftIcon="file-text" @click="openBaseScreen('设备', 'radio')">
							<u--input v-model="baseFormData.EquipmentName" placeholder="请选择设备" readonly
								border="none"></u--input>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
						<u-form-item labelWidth="100" label="点检人" borderBottom :leftIconStyle="{'font-size':'20px'}"
							leftIcon="order">
							<u--input v-model="baseFormData.CheckupMan" placeholder="自动生成" readonly
								border="none"></u--input>
						</u-form-item>
						<u-form-item labelWidth="100" label="点检日期" borderBottom :leftIconStyle="{'font-size':'20px'}"
							leftIcon="order">
							<!-- leftIcon="order" @click="AddTimeshow"> -->
							<u--input v-model="baseFormData.BillDate" placeholder="请选择点检日期" readonly
								border="none"></u--input>
						</u-form-item>

						<u-form-item labelWidth="100" label="周期" :leftIconStyle="{'font-size':'20px'}"
							prop="PeriodTypeName" required leftIcon="file-text" @click="openBaseScreen('周期', 'radio')">
							<u--input v-model="baseFormData.PeriodTypeName" placeholder="自动生成" readonly
								border="none"></u--input>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
					</u--form>
					<view class="Main_CardListBox">
						<view class="CardBox" v-for="(item,index) in tableData" :key="index">
							<view class="Main_Card_Top">
								<view class="Main_Card_LeftBox x-f">
									<view class="OrdinalBox">
										<text>{{index + 1}}</text>
									</view>
									<view class="Title_Text x-f">
										<text>点检项目</text>
									</view>
								</view>
								<!-- 
								<view class="Main_Card_RightBox">
									<view class="TypeText">
										<text>{{item.CheckupItemName}}</text>
									</view>
								</view> -->
							</view>
							<view class="CommonBox">
								<u-cell title="所属分类">
									<template #value>
										<div class="CommonBoxDiv" :style="{ width: scrollLiftWidth + 'px'}">
											{{item.EquipmentCheckTypeName}}
										</div>
									</template>
								</u-cell>
								<u-cell title="点检内容">
									<template #value>
										<div class="CommonBoxDiv" :style="{ width: scrollLiftWidth + 'px'}">
											{{item.CheckupItemName}}
										</div>
									</template>
								</u-cell>
								<u-cell title="点检方式">
									<template #value>
										<div class="CommonBoxDiv" :style="{ width: scrollLiftWidth + 'px'}">
											{{item.ProcessingMethod}}
										</div>
									</template>
								</u-cell>
								<u-cell title="点检标准">
									<template #value>
										<div class="CommonBoxDiv" :style="{ width: scrollLiftWidth + 'px'}">
											{{item.OnStandard}}
										</div>
									</template>
								</u-cell>
								<u-cell title="处理方法">
									<template #value>
										<div class="CommonBoxDiv" :style="{ width: scrollLiftWidth + 'px'}">
											{{item.CheckContent}}
										</div>
									</template>
								</u-cell>
								<u-cell title="点检结果" :border='false' class="custom-cell">
									<template slot="right-icon">
										<uni-data-checkbox v-model="item.FResult" :localdata="SpotCheckResultsList"
											:disabled="!ButtonShow" />
									</template>
								</u-cell>
							</view>

						</view>
					</view>

				</view>
				<template #bottom>
					<view class="BottomBox" :style="$utils.disposeSafeBottomFun()" v-show="ButtonShow">
						<button block @click="submit" style="width: 90%;margin: 0 auto !important;"
							class="content_bottom_primary_Btn">
							保 &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp 存
						</button>
					</view>

				</template>
			</z-paging>

		</view>

		<u-modal :show="modalshow" :title="modaltitle" :content="modalcontent" :showCancelButton='true'
			@confirm='modalconfirm' @cancel='modalshow=false'>
		</u-modal>
		<u-toast ref="uToast"></u-toast>
		<m-pda-scancode v-if="$utils.isPda()" listenName="BatchEditScan"
			:SetContent="{action:$store.state.systemConfig.sysDeviceInfo.broadcastAction,extra:$store.state.systemConfig.sysDeviceInfo.broadcastResult}"></m-pda-scancode>

	</view>

</template>

<script>
	import {
		formatDateTime,
		getFormatDateTime,
		getBefore7DateTime
	} from '@/st_device/common/base.js';
	import BaseMixin from '@/st_device/common/base.js';
	export default {
		mixins: [BaseMixin],
		data() {
			return {
				BtnShow: false, // 扫码按钮判断显示
				modalshow: false, //模态框
				modaltitle: '提示', //模态框提示语
				modalcontent: '', //模态框提示语
				rules: {
					'EquipmentName': {
						type: 'string',
						required: true,
						message: '设备不能为空',
						trigger: ['change']
					},
					'PeriodTypeName': {
						type: 'string',
						required: true,
						message: '点检周期不能为空',
						trigger: ['change']
					}
				},
				ButtonShow: true, //按钮是否显示
				baseFormData: {
					EquipmentName: '',
					EquipmentID: '',
					PeriodTypeName: '日',
					PeriodType: 'D',
					CheckupMan: '',
					BillDate: ''

				},
				SpotCheckResultsList: [], // 点检结果数组
				SpotCheckCycleList: [], // 点检周期

				tableData: [], //子表
				value1: Number(new Date()), //时间值
				Timeshow: false, //时间是否显示
				scrollLiftWidth: uni.getSystemInfoSync(), //列表高度
			};
		},
		onLoad(item) {
			var that = this
			this.initData()
			var EquipmentObj
			// 判断是否是详情页面扫码 传递对象
			if (item.EquipmentObj) {
				EquipmentObj = JSON.parse(item.EquipmentObj)
			}

			// 判断是否有主表ID
			if (item.CheckupEquipmentID) {
				that.queryList(item.CheckupEquipmentID)
			} else {
				// 点检人员
				this.baseFormData.CheckupMan = this.baseFormData.CheckupMan ? this.baseFormData.CheckupMan : this
					.$store.state.UserInfo.UserName
				// 点检人员id
				this.baseFormData.CheckupID = this.baseFormData.CheckupID ? this.baseFormData.CheckupID : this.$store
					.state.UserInfo.EmplID
				// 点检日期
				this.baseFormData.BillDate = this.baseFormData.BillDate ? this.baseFormData.BillDate :
					getFormatDateTime(new Date())
				// 判断是否是详情页面扫码 传递对象
				if (EquipmentObj) {
					this.baseFormData.EquipmentName = this.baseFormData.EquipmentName ? this.baseFormData.EquipmentName :
						EquipmentObj.EquipmentName
					this.baseFormData.EquipmentID = this.baseFormData.EquipmentID ? this.baseFormData.EquipmentID :
						EquipmentObj.EquipmentID
					that.addPeriodTypeClick()
				}

				// 判断是否有设备id和周期id
				if (item.EquipmentID && item.PeriodType) {
					that.Request.request('getEquipment', {}, (ret) => {
						if (ret.status == 200) {
							var obj = ret.data.ds.find(ite => ite.EquipmentID == item.EquipmentID)
							that.baseFormData.EquipmentName = obj.EquipmentName
							that.baseFormData.EquipmentID = obj.EquipmentID
							that.baseFormData.PeriodType = item.PeriodType
							that.addPeriodTypeClick()
						}
					})

				}
			}

		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		onUnload() {
			uni.$off('BatchEditScan');
			uni.$off('spotcheckDetail_Choice');
		},

		mounted() {
			var that = this
			that.$nextTick(() => {
				that.scrollLiftWidth = (uni.getSystemInfoSync().windowWidth) / 3
				setTimeout(() => {
					that.BtnShow = true;
				}, 500)
			})
			// PDA扫码处理
			uni.$on('BatchEditScan', function(content) {
				let scanData = that.$utils.wmsFun.scanTransf(content);
				that.scanHandler(scanData);
			})
			uni.$on('spotcheckDetail_Choice', function(ret) {
				console.log(ret);
				if (ret.type == '周期') {
					that.baseFormData.PeriodType = ret.data.ID
					that.baseFormData.PeriodTypeName = ret.data.NAME
					that.PeriodTypeClick()
				} else if (ret.type == '设备') {
					that.baseFormData.EquipmentName = ret.data.EquipmentName
					that.baseFormData.EquipmentID = ret.data.EquipmentID
					that.$refs.uForm.validateField('EquipmentName');
					that.PeriodTypeClick()
				}

			});
		},
		methods: {
			async initData() {
				// 加载公共字典数据
				await this.loadCommonDictionaries([{
						type: '保养周期',
						key: 'SpotCheckCycleList',
						cmd: 'getPeriodTypeSet',
						obj: {}
					},
					{
						type: '点检结果',
						key: 'SpotCheckResultsList',
						cmd: 'GetResultSelect',
						obj: {
							FType: '点检结果'
						}
					}
				]);
			},
			async addPeriodTypeClick() {
				var that = this
				// 直接使用缓存数据，避免重复请求
				if (!that.SpotCheckCycleList.length) {
					await that.initData();
				}
				const dictMappings = {
					PeriodType: {
						dictKey: 'SpotCheckCycle',
						targetField: 'PeriodTypeName'
					},
				};
				that.mapDictNamesForItem(that.baseFormData, dictMappings);
				that.PeriodTypeClick();
			},
			// PDA扫码处理
			scanHandler(scanData) {
				let that = this;
				console.log(scanData);
				that.DeviceIDChange(scanData.recode, 'pda')
			},
			// 扫码处理
			DeviceIDChange(res, name) {
				let that = this;

				function startsWithEQRegex(str) {
					return /^EQ/.test(str) || /^SB/.test(str);
				}
				let IsDevice = startsWithEQRegex(res)
				if (IsDevice) {
					var id = res.replace(/^.*?\|/, '')
					console.log(id);
					that.Request.request('getEquipment', {}, (ret) => {
						console.log(ret);
						if (ret.status == 200) {
							var obj = ret.data.ds.find(item => item.EquipmentID == id)
							var url = `./spotcheckDetail?EquipmentObj=${JSON.stringify(obj)}`
							uni.redirectTo({
								url: url
							});

						}
					})
				}
			},
			// 模态框关闭
			modalconfirm() {
				var that = this
				that.modalshow = false
			},
			openBaseScreen(str, type) { // 前往筛选页
				let that = this;
				let obj = null;
				let url = '/commonPage/Tool/baseScreen';
				if (this.ButtonShow) {
					if (str == '设备') {
						obj = {
							allowClear: false,
							cmd: 'getEquipment',
							type: str,
							ListeningName: 'spotcheckDetail_Choice',
							serverSearch: {
								isPaging: false, //是否分页
								searchKey: 'EquipmentName', //搜索关键词，应包含在param中
								showText: 'EquipmentName', //查询结果显示的字段
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
								ChoiceDataKey: 'EquipmentID',
								ChoiceDataData: that.baseFormData.EquipmentID,
							},
							param: {
								EquipmentName: '',
								PageIndex: 1,
								PageSize: 30
							}
						}
					} else if (str == '周期') {
						obj = {
							allowClear: false,
							cmd: 'getPeriodTypeSet',
							type: str,
							ListeningName: 'spotcheckDetail_Choice',
							serverSearch: {
								isPaging: false, //是否分页
								searchKey: 'SearchKey', //搜索关键词，应包含在param中
								showText: 'NAME', //查询结果显示的字段
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
								ChoiceDataKey: 'ID',
								ChoiceDataData: that.baseFormData.PeriodType,
							},
							param: {
								SearchKey: '',
								PageIndex: 1,
								PageSize: 30
							}
						}
					}
					this.$store.commit('ChangeAndSetStateData', {
						Name1: 'BaseScreenParm',
						data: obj
					})
					uni.navigateTo({
						url: url
					})
				}

			},


			// 获取点检项目
			PeriodTypeClick() {
				var that = this
				if (that.baseFormData.EquipmentID) {
					var obj = {
						EquipmentID: that.baseFormData.EquipmentID,
						PeriodType: that.baseFormData.PeriodType,
						FType: 'SBDJ'
					}

					that.Request.request('getCheckupItem', obj, (ret) => {
						console.log(ret);
						ret.data.ds.map((item) => {
							item.FResult = item.FResult ? item.FResult : 1
							item.CheckupItemName = item.CheckupItemName ? item.CheckupItemName : item
								.SB_CheckupItemName
							item.UpkeepEquipmentDeID = item.UpkeepEquipmentDeID ? item
								.UpkeepEquipmentDeID : 0
							item.CheckupEquipmentDeID = item.CheckupEquipmentDeID ? item
								.CheckupEquipmentDeID : 0
						})
						that.tableData = ret.data.ds
						that.$forceUpdate()
					})
				}

			},
			// 手机扫码
			scan() {
				let that = this;
				uni.scanCode({
					success: function(res) {
						console.log(res);
						that.DeviceIDChange(res.result, 'phone')

					},
					fail: function(fail) {
						console.log(fail);
					}
				});

			},

			// 获取详情数据
			queryList(id) {
				var that = this

				try {
					that.Request.request('getCheckuEquipmentDetail', {
						CheckupEquipmentID: id
					}, (ret) => {
						console.log(ret.data);
						that.ButtonShow = false
						ret.data.ds.map((item) => {
							if (item.PeriodType) {
								const dictMappings = {
									PeriodType: {
										dictKey: 'SpotCheckCycle',
										targetField: 'PeriodTypeName'
									},
								};
								that.mapDictNamesForItem(item, dictMappings);
							}
							item.BillDate = formatDateTime(item.BillDate)
						})
						that.baseFormData = ret.data.ds[0]
						that.tableData = ret.data.ds1
						that.$forceUpdate()
					})
				} catch (e) {
					console.log(e)
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},
			// 保存
			submit() {
				var that = this
				var show = true
				var msg
				this.$refs.uForm.validate().then(res => {
					if (that.tableData.length == 0) {
						show = false
						msg = '当前设备没有该点检周期'
					}
					if (show) {
						that.tableData.forEach(item => {
							if (item.ProcessingMethod == '' || item.ProcessingMethod == null) {
								item.ProcessingMethod = '@'
							}
							if (item.OnStandard == '' || item.OnStandard == null) {
								item.OnStandard = '@'
							}
						})
						var obj = {
							CheckupMan: that.baseFormData.CheckupMan,
							EquipmentID: that.baseFormData.EquipmentID,
							CheckupEquipmentID: that.baseFormData.CheckupEquipmentID ? that.baseFormData
								.CheckupEquipmentID : 0,
							PeriodType: that.baseFormData.PeriodType,
							OnStandard: that.tableData.map(item => item.OnStandard).join(','),
							ProcessingMethod: that.tableData.map(item => item.ProcessingMethod).join(','),
							UpID: that.tableData.map(item => item.UpID).join(','),
							CheckupItemID: that.tableData.map(item => item.CheckupItemID).join(','),
							FResult: that.tableData.map(item => item.FResult).join(','),
							BillDate: that.baseFormData.BillDate,
							CheckContent: that.tableData.map(item => item.CheckContent).join(','),
							CheckupEquipmentDeID: that.tableData.map(item => item.CheckupEquipmentDeID).join(
								',')
						}
						console.log(obj);
						that.Request.request('saveCheckupEquipment', obj, function(ret) {
							console.log(ret);
							if (ret.status == 200) {
								that.$refs.uToast.show({
									title: '保存',
									type: 'success',
									message: '保存成功'
								})
								that.queryList(ret.data.ds[0].CheckupEquipmentID)
							}
						})

					} else {

						that.modaltitle = '提醒'
						that.modalcontent = msg
						that.modalshow = true
					}

				}).catch(errors => {
					uni.$u.toast(errors[0].message)
				})



			},
			// 退出
			leftClick() {
				let routes = getCurrentPages(); //当前页面栈
				let prevPage = routes[routes.length - 2]
				prevPage.$vm.getList()
			}
		}
	}
</script>

<style lang="scss">
	@import "./css/index.scss";
</style>